package com.common.help;


import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.busines.dto.BaseDto;
import com.busines.dto.HelloDto;
import com.busines.dto.OwnerAndCardsDto;
import com.busines.po.StudentPo;
import com.busines.pojo.xunting.TStudent;
import com.busines.service.IRedisService;
import com.common.util.DateUtils;
import com.common.util.HttpClientUtil;
import com.common.util.RedisClient;
import com.common.util.RegexUtils;

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations={"classpath:config/applicationContext-jta.xml"})
public class TestDemo {

	@Resource(name="redisService")
	private IRedisService redisService;
	
	@Resource(name="redisClient")
	private RedisClient redisClient;
	
	@Test
	public void test1() throws Exception{
		//OutputExcelDemo.outputSchoolStudent();
		//redisService.test1();
		//redisService.setObjectCache();
		//System.out.println(null ==  redisService.getObjectCache()?null:redisService.getObjectCache().toString());
		//redisService.setObjectCacheHash();
		//System.out.println(redisService.getObjectCacheHash().toString());
//		Map<String,String> map = mapToBean(redisService.getObjectCache());
//		for(Entry<String,String> entry :map.entrySet()){
//			System.out.println(entry.getKey()+"-->"+entry.getValue());
//		}

//		StudentPo po = redisService.getStudentPoCacheByLock();
//		if(po==null){
//			return;
//		}else{
//			po.setStudentName("Frank Yang");
//			redisService.setObjectCacheHash(po);
//			redisClient.unlock(po.getRlock());
			//System.out.println(po == null?"空的":po.getRlock().getKey());
//		StudentPo po = new StudentPo();
//		redisClient.setObjectCache("po", po);
		
		
//		int i=999;
//		System.out.println("滞纳金收入"+i/100D+"元");
//		
//		
//		DecimalFormat df = new DecimalFormat("######0.00");
//		System.out.println(df.format(i/100D));
//		
//		String str = "[9,10,11]";
//		List<Integer> list1 = JSON.parseArray(str, Integer.class);
//		
//		
//		List<String> list = new ArrayList<>();
//		list.add("aa");
//		list.add("bb");
//		list.add("cc");
//		System.out.println(JSON.toJSONString(list));
		
//		List<String> list = new ArrayList<>();
//		list.add("FK20180615030111pvy4hu");
//		String apiUrl = "http://localhost:8086/qpusercenter/mepuser/updateBalanceRecord";
//		Map<String,Object> params = new HashMap<String,Object>();
//		params.put("userId", "MEP10100100");
//		params.put("tradeNos", JSON.toJSONString(list));
//		
//		HttpClientUtil.doPost(apiUrl, params);
//		Map<String,Object> params = new HashMap<String,Object>();
//		String str = "{'todayTotalcharge':'60000','balanceBsCouponFee':0,'balancePtCouponFee':0,'businessCouponFee':0,'cashBsCouponFee':0,'cashPtCouponFee':0,'localBsCouponFee':0,'localPtCouponFee':0,'parkingNo':'5227260720177','recordId':'HMDS201806151352120efdpxe9','settleDate':'2018-06-14','unblockedCardNum':0,'unobstructedCardNum':0,'userId':'MEP10100100'}";
//		params.put("jsonData",str);
//		String apiUrl = "http://localhost:8085/qpmep/connectPark/insertParkBusinessRecord";
//		System.out.println(HttpClientUtil.doPost(apiUrl, params));
		
//		Map<String, String> map = redisClient.getMap("CARE_RECORD_"+"4403050510027");
//		for(String str :map.values()){
//			System.out.println(str);
//			CareCacheInfo care = JSON.parseObject(str, CareCacheInfo.class);
//			System.out.println(care.toString());
//		}
//		Date entry = new Date();
//		Calendar c = Calendar.getInstance();
//		c.add(c.DAY_OF_MONTH, -1);
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		String time = sdf.format(c.getTime());
//		System.out.println(sdf.format(c.getTime()));
//		String start = time+" 00:00:00";
//		String end = sdf.format(entry)+" 00:00:00";
//		
//		long time1 = sdf.parse(end).getTime()-sdf.parse(start).getTime();
//		System.out.println(time1);
//		Calendar c = Calendar.getInstance();
//		String time = "2018-06-26";
//		SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
//		c.setTime(sdf.parse(time));
//		c.add(Calendar.DAY_OF_MONTH, 1);
//		System.out.println(sdf.format(c.getTime()));
//		BaseDto dto = new BaseDto();
//		List<TStudent> list = null;
//		dto.setObj(list);
//		if(dto.getObj()==null){
//			list = new ArrayList<>();
//			dto.setObj(list);
//		}
//		
//		if(null!=dto.getObj()){
//			List<TStudent> aa = (List<TStudent>)dto.getObj();
//			System.out.println(aa.get(0));
//		}
//		List<TStudent> list = new ArrayList<>();
//		TStudent t = new TStudent();
//		t.setStudentName("ah");
//		list.add(t);
//		t.setPhone("18267833805");
//		t.setStudentName("ss");
//		list.add(t);
//		System.out.println(list.toString());
//		CareCacheInfo a = new CareCacheInfo();
//		a.setCareFee(11111);
//		System.out.println(a.toString());
//		ExipreVo vo = new ExipreVo();
//		vo.setCardLicenseInfoList(Arrays.asList("粤A00001".split(",")));
//		vo.setParkingNo("PN20180517000023");
//		vo.setCardType(31);//时效卡
//		vo.setProductType(3);//畅听卡
//		vo.setUseEndTime(1530847860000L);
//		vo.setStatus(2);
//		vo.setUserCardNo("USER_CARD_NO_00000006");
//		System.out.println(JSON.toJSONString(vo));
//		
		
//		String aa = "Aaaaaa";
//		char[] aaa = aa.toCharArray();
//		aaa[0]+=32;
//		
//		System.out.println(String.valueOf(aaa));
		
		String carnumRegex = "([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领台A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领台A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1})";
		
		String license = "WJ鲁4680B";
		
		System.out.println(license.matches(carnumRegex));
		
	}
	
	private void fileup(String s){

		URL uri = this.getClass().getClassLoader().getResource(s);
		System.out.println(uri.getFile());
		File files = new File(uri.getFile());
		for(File file:files.listFiles()){
			if(file.isDirectory()){
				this.fileup(s+"/"+file.getName());
			}else{
				System.out.println(file.getName());
			}
		}
	}
	
	@Test
	public void test2(){
		Calendar recordTime = Calendar.getInstance();
        Date time = new Date(1525720850000L);// 记录生成日期
        recordTime.setTime(DateUtils.getJointDate(time, "00:00:00"));
        recordTime.set(Calendar.DAY_OF_MONTH, recordTime.get(Calendar.DAY_OF_MONTH) + 1 - 1);
        Date now = DateUtils.getJointDate(new Date(), "23:59:59");
	}
	
	@Test
	public void test3(){
		Date date = new Date(1530374399000L);
		System.out.println(date);
		String str = "a,b,c,d,e,f,g,h,i,j,k,a,b,c,d,e,f,g,h,i,j,k";
		String[] arrays = str.split(",");
		Set<String> collection = new LinkedHashSet<String>();
		CollectionUtils.mergeArrayIntoCollection(arrays, collection);
		for(Iterator<String> it = collection.iterator(); it.hasNext();){
			System.out.println(it.next());
		}
	}
	@Test
	public void test4(){
		String str = "20180510";
		String str1 = "0700";
		String str2 = "2230";
		String date1 = "2018-05-10 07:00";
		String date2 = "2018-05-10 22:30";
		
		Double a=null;
		System.out.println(null==a?0D:a);
		
		String ss="null";
		System.out.println(ss.equals("null")?0:ss);
		
		System.out.println(Double.parseDouble("0"));
		
		String fee ="2312313131";
		System.out.println(Double.parseDouble(fee)/100D);
	}
	
	@Test
	public void test5(){
		String license ="元123456";
		System.out.println(RegexUtils.checkLicense(license));
		
		String userCard = "33470253545611A";
		System.out.println(RegexUtils.checkIdCard(userCard));
		
		String mobile = "15777777777";
		System.out.println(RegexUtils.checkMobile(mobile));
	}
	
	@Test
	public void test6(){
		System.out.println(HttpClientUtil.doGet("www.baidu.com"));
		String url = "www.baidu.com";
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("name", "hello");
		params.put("password", 12345);
		StringBuffer param = new StringBuffer();
		if(params!=null&&!CollectionUtils.isEmpty(params)){
			int i=0;
			for(String key:params.keySet()){
				if(i==0){
					param.append("?");
				}else{
					param.append("&");					
				}
				param.append(key+"=").append(params.get(key));
				i++;
			}
			url += param.toString();
		}
		System.out.println(url);
	}
	
	@Test
	public void test7(){
		String url ="http://120.76.154.100:5110/product/carLicenseInfo/getInfoByLicense";
		String str = "111112211";
		String[] str1 = str.split(",");
		
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("license", "台J12345");
		map.put("parkingNo", Arrays.asList(str1));
		String aa = HttpClientUtil.doPost(url, map);
		if(StringUtils.isNotBlank(aa)){
			OwnerAndCardsDto dto = JSON.parseObject(aa, OwnerAndCardsDto.class);
			System.out.println(dto.getResult().size());
		}
		
	}
	@Test
	public void test8(){
		Random r = new Random();
		int i = r.nextInt(100);
		String aaa = redisClient.get("aaa");
		if(StringUtils.isNotBlank(aaa)){
			int a = aaa.split(",").length;
			if(a<3){
				redisClient.set("aaa", aaa+i+",");
			}
					
		}else{
			redisClient.set("aaa", "aaa,");
		}
	}
	@Test
	public void test9(){
//		String aa="29"+",";
//		String aaa = redisClient.get("aaa");
//		System.out.println(aaa.replaceAll(aa, ""));
		redisClient.set("aaa:bbb_ccc", "aaa");
	}
	
	@Test
	public void test10(){
		
		//System.out.println(bb().getRet());
	int a=0;
		for(int i=0;i<100;i++){
			int b=1;
			int c=2;
			a+=(b+c);
			if(i==3)break;
		}
		System.out.println(a);
	}
	
	
	private BaseDto bb(){
		HelloDto dto = new HelloDto();
		dto.setCc("aa");
		return dto;
	}
	
	@Test
	public void test11(){
		String str = "浙ABCDEF,浙456789,粤1234567";
		String license = "浙ABCDEF,";
		System.out.println(str.replaceAll(license, ""));
		
		String str1 ="aa";
		System.out.println(str1.split(","));
		List list = Arrays.asList(str1.split(","));
		System.out.println(list);
	}
	@Test
	public void test12(){
			List<String> list = new ArrayList<String>();
			list.add("a");
			list.add("b");
			list.add("c");
			 System.out.println(list.toString());
			 
			 System.out.println(StringUtils.join(list, ","));
			 
			 list.toArray();
			
	}
	public Map<String,String> mapToBean(Object obj){
		if(obj !=null){
		//将对象转为map
		Map<String,String> map = new HashMap<String,String>();
		
		Class<?> clazz = obj.getClass();
		
		Field[] fields = clazz.getDeclaredFields();
		for(Field field : fields ){
			PropertyDescriptor pd;
			try {
				if(field.getName().equals("serialVersionUID")){
					continue;
				}
				pd = new PropertyDescriptor(field.getName(),clazz);
				Method method = pd.getReadMethod();
				Object value = method.invoke(obj);
				if(value !=null){
					if(value instanceof Date){
						value = DateUtils.getStrDate((Date)value);
					}else if(value instanceof String){
						value = (String)value;
					}else if(value instanceof Object){
						value = JSON.toJSONString(value);
					}
				}
				map.put(field.getName(), value+"");
			} catch (IntrospectionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return map;
		}
		return null;
	}


	@Test
	public void test13(){
		RandomAccessFile aFile =null;
		try {
			aFile = new RandomAccessFile("C:/Users/youxiang/Desktop/nio-data.txt", "rw");
			FileChannel inChannel = aFile.getChannel();
			
			ByteBuffer byteBuffer = ByteBuffer.allocate(14);
			
			int byt = inChannel.read(byteBuffer);
			
			while(byt!=-1){
				System.out.println("Read " + byt);
				byteBuffer.flip();
				
				while(byteBuffer.hasRemaining()){
					System.out.println((char)byteBuffer.get());
				}
				byteBuffer.clear();
				
				byt = inChannel.read(byteBuffer);
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(aFile!=null){
				try {
					aFile.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		
	}
	
	@Test
	public void test14(){
		RandomAccessFile rm= null;
		FileChannel channel = null;
		try {
			rm = new RandomAccessFile("d:/a.txt", "rw");
			channel = rm.getChannel();
			String data = "hello my name is hm "+System.currentTimeMillis();
			
			ByteBuffer buf = ByteBuffer.allocate(1024);
			buf.put(data.getBytes());
			buf.flip();
			
			while(buf.hasRemaining()){
				channel.write(buf);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(rm!=null){
				try {
					rm.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(channel!=null){
				try {
					channel.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	@Test
	public void test15(){
		SocketChannel serverChannel = null;
		try {
			serverChannel = SocketChannel.open();
			serverChannel.connect(new InetSocketAddress("www.fortify.net", 443));
			
			ByteBuffer byt = ByteBuffer.allocate(1024);
			int b = serverChannel.read(byt);
			
			while(b!=-1){
				byt.flip();
				if(byt.hasRemaining()){
					System.out.println((char)byt.get());
				}
				byt.clear();
				
				b = serverChannel.read(byt);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Test
	public void test16(){
		//System.out.println(Integer.toBinaryString(100));
		String a = "511";
		System.out.println(a.startsWith("4"));
		System.out.println(a.startsWith("3"));
		
		List<String> list = new ArrayList<>();
		list.add("aa");
		list.add("bb");
		AAA aa = new AAA();
		aa.setParks(list);
		aa.setLicense("台A00001");
System.out.println(JSON.toJSONString(aa));
	}
	class AAA{
		String license;
		List<String> parks;
		public String getLicense() {
			return license;
		}
		public void setLicense(String license) {
			this.license = license;
		}
		public List<String> getParks() {
			return parks;
		}
		public void setParks(List<String> parks) {
			this.parks = parks;
		}
	}
}
